<template>
  <el-card shadow="hover" :body-style="{ padding: '20px' }">
    <template #header>
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTrademark"
        >添加</el-button
      >
    </template>
    <!-- 表单 -->
    <el-table :style="{ marginBottom: '30px' }" :data="tabelData" border stripe>
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column prop="tmName" label="品牌名称"></el-table-column>
      <el-table-column prop="logoUrl" label="品牌LOGO">
        <!-- 使用作用域插槽接收到传递的数据 -->
        <template #default="{ row }">
          <!-- <img height="60" :src="row.logoUrl" alt="" /> -->
          <el-image
            style="width: 100px; height: 100px"
            :src="row.logoUrl"
            lazy
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <!-- 使用默认插槽 接收传递过来的值 -->
        <template #default="{ row }">
          <el-button
            type="warning"
            size="default"
            :icon="Edit"
            @click="upDateTrademark(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="default"
            :icon="Delete"
            @click="deleteTrademark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 页码 -->
    <el-pagination
      v-model:page-size="limit"
      v-model:current-page="page"
      :page-sizes="[3, 5, 10, 15]"
      :pager-count="5"
      layout="sizes,prev, pager, next,"
      :total="total"
      background
    />
  </el-card>
  <!-- 点击添加弹出对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :title="newTrademark.id ? '修改品牌' : '新增品牌'"
  >
    <el-form :model="newTrademark" :rules="trademarkRule" ref="ruleFormRef">
      <el-form-item
        label="品牌名称"
        prop="tmName"
        :label-width="formLabelWidth"
      >
        <el-input autocomplete="off" v-model="newTrademark.tmName" />
      </el-form-item>
      <el-form-item
        label="品牌logo"
        prop="logoUrl"
        :label-width="formLabelWidth"
      >
        <!-- 上传 -->
        <!-- 出现跨域问题?因为图片在上传后就发送请求且不仅过我们的axios 需要修改请求地址 -->
        <el-upload
          class="avatar-uploader"
          :action="`${baseUrl}/admin/product/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="newTrademark.logoUrl"
            :src="newTrademark.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button size="default" @click="dialogFormVisible = false"
          >取消</el-button
        >
        <el-button size="default" type="primary" @click="addorUpdateTrademark"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>

<script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import type { reqTrademarkReturnRecordsType } from "@/api/trademark";
import { ElMessage, ElMessageBox } from "element-plus";
//elePlus的类型限制
import type { UploadProps, FormRules, FormInstance } from "element-plus";
//引入type
import type { reqTrademarkReturnItemType } from "@/api/trademark";
//引入api
import {
  requestTrademarkList,
  requestAddTrademark,
  requestUpdateTrademark,
  requestDeleteTrademark,
} from "@/api/trademark";

//拿到env的环境变量
const baseUrl = import.meta.env.VITE_API_URL;
//弹窗中添加图片的事件函数
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  //响应回来的数据设置给logoUrl
  newTrademark.value.logoUrl = response.data;
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
//初始化
onMounted(() => {
  //调用获取品牌列表的功能函数
  getTrademarkList();
});

//1.table的逻辑
//定义table数据响应式
const tabelData = ref<reqTrademarkReturnRecordsType>([]);

//2.页码逻辑
//页码的数据和类型
interface pageDateType {
  page: number;
  limit: number;
  total: number;
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 3,
  total: 100,
});
//解构出页码的属性
const { page, limit, total } = toRefs(pageDate.value);

//3.获取品牌列表
//封装获取品牌列表的功能函数
const getTrademarkList = async () => {
  //发送请求
  const result = await requestTrademarkList({
    page: page.value,
    limit: limit.value,
  });
  //把请求回来的值设置给响应数据
  tabelData.value = result.records;

  total.value = result.total;
};

//监听页码的改变 然后重新发送请求
watch([page, limit], () => {
  getTrademarkList();
});

//弹窗逻辑
//定义弹窗是否弹出默认值为false
const dialogFormVisible = ref(false);
//定义fromlabel宽度
const formLabelWidth = "140px";

//定义新添加品牌的数据响应式
const newTrademark = ref<reqTrademarkReturnItemType>({
  tmName: "",
  logoUrl: "",
  id: 0,
});
//4.添加品牌函数
const addTrademark = () => {
  //点击的时候弹窗弹出
  dialogFormVisible.value = true;
  //清除遗留的表单校验规则
  ruleFormRef.value?.clearValidate();
  //清空回填的数据
  newTrademark.value = {
    id: 0,
    tmName: "",
    logoUrl: "",
  };
};
//5.修改品牌函数
const upDateTrademark = (row: reqTrademarkReturnItemType) => {
  //点击的时候弹窗弹出
  dialogFormVisible.value = true;
  //清除遗留的表单校验规则
  ruleFormRef.value?.clearValidate();
  //传递的数据就是当前的品牌所有信息浅拷贝 需要数据回填
  newTrademark.value = { ...row };
};
//6.添加或修改事件函数
//获取from表单的是咧
const ruleFormRef = ref<FormInstance>();
//事件函数
const addorUpdateTrademark = async () => {
  try {
    //先进行全局校验
    await ruleFormRef.value?.validate();
    //弹窗关闭
    dialogFormVisible.value = false;
    //我们需要判断当前点击的是新增还是修改 如果是修改的话则一定有Id保存在newTrademark中
    try {
      if (newTrademark.value.id) {
        //发送修改请求
        //收集表单数据发送请求
        await requestUpdateTrademark(newTrademark.value);
        ElMessage.success("修改成功");
      } else {
        //发送新增请求
        await requestAddTrademark(newTrademark.value);
        ElMessage.success("新增成功");
      }
      //重新获取数据
      getTrademarkList();
    } catch (e) {
      ElMessage.error(newTrademark.value.id ? "修改失败" : "新增失败");
    }
  } catch (e) {}
};

//删除品牌事件函数
const deleteTrademark = async (row: reqTrademarkReturnItemType) => {
  //获取到Id
  const id = row.id;
  ElMessageBox.confirm("确定删除该品牌吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await requestDeleteTrademark(id);
        ElMessage.success("删除成功");
        //重新获取数据
        getTrademarkList();
      } catch (e) {}
    })
    .catch(() => {});
};

//添加品牌权限校验逻辑
//自定义表单规则函数
// const checkTmNameLength = (rule: any, value: string, callback: any) => {
//   /*
//     value是当前需要被检验的值
//     callback是回调函数,如果有参数则代表错误信息,如果没有参数则代表放行
//   */
//   if (value.length < 2 || value.length > 5) {
//     callback("长度必须是2-5");
//   } else {
//     callback();
//   }
// };
const trademarkRule = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须填写品牌名称", trigger: "blur" },
    // { min: 2, max: 5, message: "长度必须是2-5", trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "必须上传图片", trigger: "change" }],
});
/*
//最完成的解构ref属性的带类型的写法
  const {
    page,
    limit,
    total,
  }: { page: Ref<number>; limit: Ref<number>; total: Ref<number> } =
    toRefs<pageDateType>(pageDate.value);

  //对象解构如何限制类型(一般不会限制,因为都能推断出来)
  const o = { a: 1, b: 2 };
  const { a, b }: { a: number; b: number } = o;
  console.log(a, b);
*/
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
